package com.app.shop.service.system.impl;

import com.app.shop.util.UserEntity;
import com.app.shop.dao.system.SysMenuMapper;
import com.app.shop.dao.system.SysUserMapper;
import com.app.shop.entity.SysUser;
import com.app.shop.entity.SysUserExample;
import com.app.shop.service.system.SecurityService;
import com.app.shop.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 用户登录Service模块
 *
 * @author chenliwei
 * @version v1.0 2017-11-5
 */
@Service("securityService")
public class SecurityServiceImp implements SecurityService {


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 用户登录模块
     * @param username 登录账号
     * @return 登录用户信息
     * @throws UsernameNotFoundException 用户名不存在异常
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //如果用户登上次数超过限制直接进行屏蔽
        if(!LoginUtil.loginFilter(username)){
            throw new UsernameNotFoundException("用户账号冻结,请15分钟后操作！");
        }
        //每次登陆都会进行记录，登陆成功会自动清理失败信息
        LoginUtil.loginFail(username);
        //查询用户信息
        SysUserExample sysUserExample=new SysUserExample();
        sysUserExample.createCriteria().andUsernameEqualTo(username);
        List<SysUser> sysUserList= sysUserMapper.selectByExample(sysUserExample);
        UserEntity userEntity=null;
        if(sysUserList.size()==1){
            userEntity=new UserEntity();
            userEntity.setUsername(sysUserList.get(0).getUsername());
            userEntity.setPassword(sysUserList.get(0).getPassword());
            userEntity.setUserId(sysUserList.get(0).getUserId());
            userEntity.setStatus(sysUserList.get(0).getStatus());
            userEntity.setName(sysUserList.get(0).getName());
            //将用户菜单权限信息存储到内存
            LoginUtil.putMenuList(sysUserList.get(0).getUserId(),sysMenuMapper.selectByUserId(sysUserList.get(0).getUserId()));
        }
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名或密码不正确！");
        }
        return userEntity;
    }

}
